/*
 * @desc 图片剪切
 * */
define(['jquery', 'tool', 'jcrop'], function($, tool) {
    var croper = {
        //创建
        build : function(options){
            var me = this, $el =  tool.get$el(options.el), temp;
            if($el.length == 1){
                temp = new Croper(options);
                return temp;
            }else if($el.length > 1){
                var arr = [];
                $el.each(function(){
                    var opts = $.extend({}, options, {el : this});
                    temp = new Croper(opts);
                    arr.push(temp);
                });
                return arr;
            }
            return options;
        }

    };

    function Croper(){
        this.init.apply(this, arguments);
    }

    Croper.prototype = {
        init : function(options){
            var me = this, jcrop;
            options.newSetSelect = options.setSelect;
            delete(options.setSelect);
            options = $.extend({}, Croper.defaults, options);
            var $img = tool.get$el(options.el);
            this.setContainer($img, options);
            jcrop = $.Jcrop($img.get(0), options);
            for(var i in me){
                jcrop[i] = me[i];
            }
            for(var i in jcrop){
                me[i] = jcrop[i];
            }
            this.initCrop();
        },

        //初始化剪切设置
        initCrop : function(){
            this.setPreview();
        },

        //设置操作容器
        setContainer : function($img, options){
            var $container = $(
                    '<div class="croper">' +
                    '<div class="image-container"></div>' +
                    '<div class="preview-container"></div>' +
                    '<input class="croper-width" name="' + (options.widthField || 'width') + '" type="hidden" />' +
                    '<input class="croper-height" name="' + (options.heightField || 'height') + '" type="hidden" />' +
                    '<input class="croper-w" name="' + (options.wField || 'w') + '" type="hidden" />' +
                    '<input class="croper-h" name="' + (options.hField || 'h') + '" type="hidden" />' +
                    '<input class="croper-xstart" name="' + (options.xstartField || 'xstart') + '" type="hidden" />' +
                    '<input class="croper-ystart" name="' + (options.ystartField || 'ystart') + '" type="hidden" />' +
                    '<input class="croper-xend" name="' + (options.xendField || 'xend') + '" type="hidden" />' +
                    '<input class="croper-yend" name="' + (options.yendField || 'yend') + '" type="hidden" />' +
                    '</div>');
            $img.after($container).addClass('croper-image');
            $img.appendTo($container.find('.image-container'));

            this.$container = $container;
        },

        //设置预览
        setPreview : function(){
            var me = this,
                options = this.getOptions(), setting = {},
                selectWidth = 0, selectHeight = 0,
                aspectRatio = options.aspectRatio || 0,
                $previewContainer = this.$container.find('.preview-container');
            $.each(options.preview, function(i, item){
                var $preview, $img;
                if(typeof item.el == 'string'){
                    $preview = $(item.el);
                }else{
                    $preview = $('<div class="over-hidden preview preview-' + (i) + '"></div>').appendTo($previewContainer);
                }
                $img = $preview.find('img');
                $img = $img.length ? $img : $('<img src="' + $(options.el).attr('src') + '" />').appendTo($preview);
                $preview.css({
                    width : item.width + 'px',
                    height : item.height + 'px'
                });
                item.$img = $img;

                if(!i){
                    selectWidth = item.width;
                    selectHeight = item.height;
                    if(!aspectRatio) aspectRatio = item.width / item.height;
                }
            });

            setting.aspectRatio = aspectRatio;
            if(options.cropedSize && !aspectRatio){
                setting.aspectRatio = options.cropedSize[0] / options.cropedSize[1];
                if(options.trueSize && options.scaledSize){
                    setting.setSelect = [0, 0, options.cropedSize[0] * (options.trueSize[0] / options.scaledSize[0]), options.cropedSize[1] * (options.trueSize[1] / options.scaledSize[1])];
                }
            }else{
                setting.setSelect = options.newSetSelect || [0, 0, 20000, 20000];
            }
            this.setOptions(setting);
        },

        //预览
        previewImage : function(c){
            if (parseInt(c.w) > 0) {
                var bounds = this.getBounds(),
                    boundx = bounds[0],
                    boundy = bounds[1],
                    options = this.getOptions(),
                    select = this.getCropData();
                $.each(options.preview, function (i, item) {
                    $img = item.$img;
                    $img.css({
                        width: Math.round(item.width * boundx / c.w) + 'px',
                        height: Math.round(item.height * boundy / c.h) + 'px',
                        marginLeft: '-' + Math.round(item.width * c.x / c.w) + 'px',
                        marginTop: '-' + Math.round(item.height * c.y / c.h) + 'px'
                    });
                });
                this.setCropValue(options, select);
            }
        },

        //设置剪切值
        setCropValue : function (options, select){
            this.$container.find('.croper-width').val(select.width);
            this.$container.find('.croper-height').val(select.height);
            this.$container.find('.croper-w').val(select.w);
            this.$container.find('.croper-h').val(select.h);
            this.$container.find('.croper-xstart').val(select.x);
            this.$container.find('.croper-ystart').val(select.y);
            this.$container.find('.croper-xend').val(select.x2);
            this.$container.find('.croper-yend').val(select.y2);
        },

        //获取剪切数据
        getCropData : function(){
            var options = this.getOptions(),
                select = this.tellScaled(),
                imgEl = $(options.el).get(0),
                newImg = new Image();
            newImg.src = imgEl.src;
            select.width = imgEl.width;
            select.height = imgEl.height;
            select.naturalWidth = newImg.width;
            select.naturalHeight = newImg.height;

            var previews = [];
            $.each(options.preview, function (i, item) {
                previews.push([item.width, item.height]);
            });
            select.preview = previews;

            return select;
        },

        //保存
        save : function(options){
            options = options || {};
            var opts = this.getOptions(),
                postData = opts.postData,
                data = this.getCropData();
            options = $.extend(options, {
                url : options.url || opts.url,
                success : typeof options.success == 'function' ? options.success : typeof opts.success == 'function' ? opts.success : function(){},
                error : typeof options.error == 'function' ? options.error : typeof opts.error == 'function' ? opts.error : function(){},
                complete : typeof options.complete == 'function' ? options.complete : typeof opts.complete == 'function' ? opts.complete : function(){},
                data : $.extend(data, postData, options.data)
            });
            require(['ajaxer'], function(ajaxer){
                ajaxer.ajax(options);
            });
        }

    };

    //默认配置
    Croper.defaults = {
        el: null,//需要剪切图片元素
        url : '',//存储剪切数据地址
        postData : null,//额外传输的数据
        preview : [
            //{el: null, width: 0, height: 0}
        ],//预览图片元素数组
        allowSelect: true,//允许新选框
        allowMove: true,//允许选框移动
        allowResize: true,//允许选框缩放
        trackDocument: true,//拖动选框时，允许超出图像以外的地方时继续拖动。
        baseClass: 'jcrop',//基础样式名前缀。说明：class="jcrop-holder"，更改的只是其中的 jcrop。例：假设值为 "test"，那么样式名会更改为 "test-holder"
        addClass: null,//添加样式。例：假设值为 "test"，那么会添加样式到class="jcrop-holder test"
        bgColor: 'black',//背景颜色。颜色关键字、HEX、RGB 均可。
        bgOpacity: 0.6,//背景透明度
        bgFade: false,//使用背景过渡效果
        borderOpacity: 0.4,//选框边框透明度
        handleOpacity: 0.5,//缩放按钮透明度
        handleSize: 9,//缩放按钮大小
        aspectRatio: 0,//选框宽高比。说明：width/height
        keySupport: true,//支持键盘控制。按键列表：上下左右（移动选框）、Esc（取消选框）
        createHandles: ['n', 's', 'e', 'w', 'nw', 'ne', 'se', 'sw'],//设置边角控制器
        createDragbars: ['n', 's', 'e', 'w'],//设置边框控制器
        createBorders: ['n', 's', 'e', 'w'],//设置边框
        drawBorders: true,//绘制边框
        dragEdges: true,//允许拖动边框
        fixedSupport: true,//支持 fixed，例如：IE6、iOS4
        touchSupport: null,//支持触摸事件
        shade: null,//使用更好的遮罩
        boxWidth: 0,//画布宽度
        boxHeight: 0,//画布高度
        boundary: 2,//边界。说明：可以从边界开始拖动鼠标选择裁剪区域
        fadeTime: 400,//过度效果的时间
        animationDelay: 20,//动画延迟
        swingSpeed: 3,//过渡速度
        minSelect: [0, 0],//选框最小选择尺寸。说明：若选框小于该尺寸，则自动取消选择
        maxSize: [0, 0],//选框最大尺寸
        minSize: [0, 0],//选框最小尺寸
        //scaledSize : [100, 100],//实际图的缩放宽高
        //cropedSize : [100, 100],//剪切宽度
        //trueSize : [100, 100],//实际宽高
        //选框改变时的事件
        onChange: function (c) {
            this.previewImage(c);
        },
        //选框选定时的事件
        onSelect: function () {
        },
        //在选框内双击时的事件
        onDblClick: function () {
        },
        //取消选框时的事件
        onRelease: function () {
            this.setCropValue(this.getOptions(), {});
        }
    };

    return croper;
});